<template>
  <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="queryInfo.query" placeholder="请输入搜索内容">
            <el-button slot="append" type="primary" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" style="width: 100%" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeState(scope.row)"
              active-color="#13ce66"
              inactive-color="#dcdfe6"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="changeUser(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete-solid"
              size="mini"
              @click="removeUser(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="setUserMethod(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="addUserVisible" width="50%" @close="closeAdd">
      <el-form :model="addForm" :rules="addRules" ref="addRuleForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAdd">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改用户 -->
    <el-dialog title="修改用户" :visible.sync="changeUserVisible" width="50%" @close="closeChange">
      <el-form :model="changeForm" :rules="changeRules" ref="changeRuleForm" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="changeForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="changeForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="changeForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeChange">取 消</el-button>
        <el-button type="primary" @click="changeUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="setUserDialogVisible" width="50%" @close="resetDialog">
      <div>
        <p class="margin-b">当前的用户：{{dialogUser.username}}</p>
        <p class="margin-b">当前的角色：{{dialogUser.role_name}}</p>
        <span>分配新角色:</span>
        <el-select v-model="setUser" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "users",
  data() {
    var validateEmail = (rule, value, callback) => {
      //邮箱校验规则
      var emailReg = /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/; //邮箱正则表达式
      if (value === "") {
        return callback(new Error("请输入邮箱"));
      } else if (!emailReg.test(value)) {
        callback(new Error("请输入正确邮箱"));
      } else {
        callback();
      }
    };
    var validateMobile = (rule, value, callback) => {
      //手机校验规则
      var phoneReg = /^1[3456789]\d{9}$/;
      if (value === "") {
        return callback(new Error("请输入手机号"));
      } else if (!phoneReg.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      queryInfo: {
        query: "", //查询参数
        pagenum: 1, //当前页码
        pagesize: 2 //每条显示页数
      },
      userList: [], //用户表格数据
      total: 0, //总条数,
      addUserVisible: false, //添加用户对话框
      addForm: {
        //添加用户表单数据
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      addRules: {
        //添加用户校验规则
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        email: [{ validator: validateEmail, trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }]
      },
      changeUserVisible: false, //修改用户对话框
      changeForm: {
        //修改用户数据
        username: "",
        email: "",
        mobile: ""
      },
      changeRules: {
        //修改用户校验规则
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        email: [{ validator: validateEmail, trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }]
      },
      setUserDialogVisible: false, //控制修改角色对话框
      rolesList: [], //角色列表数据
      dialogUser: {}, //分配角色对话框数据
      setUser: "" //修改角色数据
    };
  },
  methods: {
    async getUserList() {
      //角色列表表单数据
      const { data: res } = await this.$axios.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status === 200) {
        this.userList = res.data.users;
        this.total = res.data.total;
      } else {
        this.$message.error("获取列表失败");
      }
    },
    handleSizeChange(newSize) {
      //pageSize(页数) 改变时会触发
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      //currentPage(当前页) 改变时会触发
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    addUser() {
      //添加用户
      this.$refs.addRuleForm.validate(async vaild => {
        if (!vaild) {
          return;
        } else {
          const { data: res } = await this.$axios.post("users", this.addForm);
          if (res.meta.status === 201) {
            this.$message.success("添加成功");
            this.getUserList();
          } else {
            this.$message.error(res.meta.msg);
          }
        }
        this.addUserVisible = false; //关闭对话框
        this.$refs.addRuleForm.resetFields(); //重置表单
      });
    },
    closeAdd() {
      //关闭添加用户对话框
      this.addUserVisible = false;
      this.$refs.addRuleForm.resetFields(); //重置表单
    },
    closeChange() {
      //关闭修改用户对话框
      this.changeUserVisible = false;
      this.$refs.changeRuleForm.resetFields(); //重置表单
    },
    async changeState(scope) {
      //修改用户状态
      const { data: res } = await this.$axios.put(
        `users/${scope.id}/state/${scope.mg_state}`
      );
      if (res.meta.status === 200) {
        return this.$message.success("修改用户状态成功");
      } else {
        window.console.log(res.meta.status)
        scope.mg_state = !scope.mg_state;
        // return this.$message.success("修改用户状态失败");
      }
    },
    async changeUser(info) {
      //修改用户
      this.changeUserVisible = true;
      const { data: res } = await this.$axios(`users/${info}`);
      if (res.meta.status === 200) {
        this.changeForm = res.data;
      } else {
        this.$message.error("获取失败");
      }
    },
    changeUserInfo() {
      //修改用户数据
      this.$refs.changeRuleForm.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$axios.put(
            `users/${this.changeForm.id}`,
            this.changeForm
          );
          if (res.meta.status === 200) {
            this.$message.success("更新用户成功");
            this.changeUserVisible = false; //关闭对话框
            this.getUserList(); //更新数据
          } else {
            this.$message.error("更新用户失败");
          }
        }
      });
    },
    async removeUser(id) {
      //删除用户
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        this.$message.error("已取消删除");
      });
      if (res == "confirm") {
        const { data: res } = await this.$axios.delete(`users/${id}`);
        if (res.meta.status === 200) {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getUserList();
        }
      }
    },
    async setUserMethod(User) {
      //分配角色
      this.dialogUser = User;
      this.setUserDialogVisible = true;
      const { data: res } = await this.$axios.get("roles");
      this.rolesList = res.data;
    },
    async setUserBtn() {
      //分配角色确定按钮
      if (!this.setUser) return;
      const { data: res } = await this.$axios.put(
        `users/${this.dialogUser.id}/role`,
        {
          rid: this.setUser.id
        }
      );
      if (res.meta.status === 200) {
        this.$message.success("分配角色成功");
      } else {
        this.$message.error(res.meta.msg);
      }
      this.setUserDialogVisible = false;
    },
    resetDialog() {
      //关闭分配角色对话框重置表单数据
      this.dialogUser = "";
      this.setUser = "";
    }
  },
  created() {
    this.getUserList();
  }
};
</script>

<style scoped>
.el-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
}
.margin-b {
  margin-bottom: 20px;
}
</style>
